//author:kakake
class tspayService {
    public data = {
        dbConn: TSLobsterAPI.Program.GetDbConn(),
        WorkId: 1
    }

    constructor(workid: number) {
        this.data.WorkId = workid;

        this.MchModel.WorkId = this.data.WorkId;
        this.PaymentModel.WorkId = this.data.WorkId;
    }

    public MchModel = {
        model: {
            ID: 0,
            SubMchId: "",
            SubMchName: "",
            Purpose: "",
            Keys: "",
            WorkId: 1,
            DelFlag: 0,
            PassWord: ""
        },                          //实体模型
        tablename: "Pay_Mch",         //表名
        key: "ID",                  //主键字段
        val: "0",                   //主键值
        objval: {},                 //实体值
        where: "",                  //查询条件
        pageinfo: {},               //分页对象 
        WorkId: 1
    }

    public PaymentModel = {
        model: {
            PaymentId: 0,
            AppID: "",
            AppSecret: "",
            ApiKey: "",
            MchId: "",
            SubMchId: "",
            NotifyUrl: "",
            BusinessNotifyUrl: "",
            RefundNotifyUrl: "",
            BusinessRefundNotifyUrl: "",
            ApiClientCert: "",
            PayType: 0,
            IsUse: 0,
            ImgUrl: "",
            Memo: ""
        },                          //实体模型
        tablename: "Pay_PaymentType",         //表名
        key: "PaymentId",                  //主键字段
        val: "0",                   //主键值
        objval: {},                 //实体值
        where: "",                  //查询条件
        pageinfo: {},               //分页对象 
        WorkId: 1
    }

    generateTimeReqestNumber() {

        var date = new Date();
        return date.getFullYear().toString() + this.pad2(date.getMonth() + 1) + this.pad2(date.getDate()) + this.pad2(date.getHours()) + this.pad2(date.getMinutes()) + this.pad2(date.getSeconds());
    }

    pad2(n) { return n < 10 ? '0' + n : n + '' }
}

/**
 * 商户号服务
 */
class mchService {
    public data = {
        dbConn: TSLobsterAPI.Program.GetDbConn(),
        WorkId: 1,
        AppId: 1
    }

    public service: tspayService;
    public dao: tspayDao;

    constructor(workid: number, appid: number) {
        this.data.WorkId = workid;
        this.data.AppId = appid;

        this.service = new tspayService(this.data.WorkId);
        this.dao = new tspayDao(this.data.WorkId);

    }


    /**
     * 支付渠道设置
     */
    getmchlist(page, limit, searchkey) {
        var pageInfo = {
            key: "Id",
            page: page,
            perPage: limit,
            totalRecord: 100
        };

        let strsql = "select * from Pay_Mch where SubMchId like @searchkey or SubMchName like @searchkey";
        let dbparam = {
            searchkey: "%" + searchkey + "%"
        }

        let data = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, dbparam, pageInfo);

        return { data: data, count: pageInfo.totalRecord };
    }
    /**
     * 保存支付渠道
     */
    savemch(mchobj) {

        if (parseInt(mchobj.ID) == 0) {//新增
            var subMchId = this.service.generateTimeReqestNumber() + Math.ceil(Math.random() * 1000000);
            mchobj.SubMchId = subMchId;
            mchobj.DelFlag = 0;
            mchobj.PassWord = TSLobsterAPI.Utils.DesEncrypt("123456");
            this.service.MchModel.objval = mchobj;
        }
        else {//修改
            this.service.MchModel.val = mchobj.ID;
            let _mchobj = TSLobsterAPI.DbHelper.GetModel(this.data.dbConn, this.service.MchModel);
            _mchobj.SubMchName = mchobj.SubMchName;
            _mchobj.Purpose = mchobj.Purpose;
            _mchobj.Keys = mchobj.Keys;
            this.service.MchModel.objval = _mchobj;
        }

        TSLobsterAPI.DbHelper.SaveModel(this.data.dbConn, this.service.MchModel);
        return { result: true };
    }

    /**
     * 设置商户号密码
     */
    setpwd(model) {

        var strsql = "select * from Pay_Mch where SubMchId=@SubMchId";

        var oldmch = TSLobsterAPI.DbHelper.DbGetJsonObject(this.data.dbConn, strsql, { SubMchId: model.SubMchId });
        if (oldmch) {
            if (TSLobsterAPI.Utils.DesEncrypt(model.oldpassword) != oldmch.PassWord) {
                throw "原始密码错误";
            }

            if (TSLobsterAPI.Utils.DesEncrypt(model.newpassword) == oldmch.PassWord) {
                throw "新密码不能和原始密码一样";
            }

            strsql = "update pay_Mch set PassWord =@password where SubMchId = @SubMchId"
            let dbparams = {
                SubMchId: model.SubMchId,
                password: TSLobsterAPI.Utils.DesEncrypt(model.newpassword)
            }
            TSLobsterAPI.DbHelper.DbExecuteUpdate(this.data.dbConn, strsql, dbparams);
        } else {
            throw '找不到数据';
        }
    }
    /**
     * 停用启用商户号
     */
    setdelflag(id, status) {
        var strsql = "UPDATE Pay_Mch SET DelFlag=@status WHERE ID=@id";
        TSLobsterAPI.DbHelper.DbExecuteUpdate(this.data.dbConn, strsql, { id: id, status: status });
        return { result: true };
    }
    /**
     * 获取支付方式配置
     */
    getpaymentlist(subMchId) {
        var strsql = "select * from  Pay_PaymentType where SubMchId=@subMchId";

        var data = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, { subMchId: subMchId });
        return { data: data };
    }
    /**
     * 保存支付方式配置
     */
    savepayment(model) {
        var list = JSON.parse(model.paymentlist);
        list.forEach(a => {
            this.service.PaymentModel.objval = a;
            TSLobsterAPI.DbHelper.SaveModel(this.data.dbConn, this.service.PaymentModel);
        })
    }

}

/**
 * 支付记录服务
 */
class payService {
    public data = {
        dbConn: TSLobsterAPI.Program.GetDbConn(),
        WorkId: 1,
        AppId: 1
    }

    public service: tspayService;
    public dao: tspayDao;

    constructor(workid: number, appid: number) {
        this.data.WorkId = workid;
        this.data.AppId = appid;

        this.service = new tspayService(this.data.WorkId);
        this.dao = new tspayDao(this.data.WorkId);

    }


    /**
     * 获取支付交易记录
     */
    getpaylist(page, limit, orderNo, paystate, orderType, sdate, edate) {
        var pageInfo = {
            key: "Id",
            page: page,
            perPage: limit,
            totalRecord: 100
        };

        var strsql = "SELECT * ,isnull( (select sum(RefundFee) from Pay_RefundOrder where OrderNo=a.OrderNo and RefundStatus=1),0.00) as RefundFee  from Pay_Order a WHERE a.WorkId=@workid ";
        var dbparams = {
            workid: this.data.WorkId,
            orderNo: '%' + orderNo + '%',
            paystate: paystate,
            orderType: orderType,
            sdate: sdate,
            edate: edate
        }

        if ((orderNo || "") != "") {
            strsql += " and a.OrderNo Like @orderNo or a.BusinessOrderNo Like @orderNo ";
        }
        if (parseInt(paystate) > -1) {
            strsql += " and a.PayState =  @paystate ";
        }
        if (parseInt(orderType) > -1) {
            strsql += " and a.orderType = @orderType ";
        }
        if ((sdate || "") != "") {
            strsql += " and a.OrderDate >= @sdate ";
        }
        if ((edate || "") != "") {
            strsql += " and a.OrderDate <= @edate ";
        }

        var data = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, dbparams, pageInfo);
        return { data: data, count: pageInfo.totalRecord };
    }

    /**
     * 后台退款
     */
    refundforself(model) {

        try {
            this.data.dbConn.BeginTransaction();
            var strsql = "select * from Pay_Order where SubMchId=@SubMchId and OrderNo=@OrderNo";
            var dbparams = {
                SubMchId: model.SubMchId,
                OrderNo: model.OrderNo,
                PayType: model.PayType
            }

            var order = TSLobsterAPI.DbHelper.DbGetJsonObject(this.data.dbConn, strsql, dbparams);
            if (!order.ID) {
                throw '订单不存在';
            }
            strsql = "select * from Pay_Mch where SubMchId=@SubMchId";

            var mch = TSLobsterAPI.DbHelper.DbGetJsonObject(this.data.dbConn, strsql, dbparams);
            if (!mch.ID) {
                throw '配置错误';
            }

            if (TSLobsterAPI.Utils.DesEncrypt(model.PassWord) != mch.PassWord) {
                throw '密码错误';
            }
            strsql = "select * from Pay_PaymentType where SubMchId=@SubMchId and PayType=@PayType";

            var payment = TSLobsterAPI.DbHelper.DbGetJsonObject(this.data.dbConn, strsql, dbparams);
            if (!payment.PaymentId) {
                throw '配置错误';
            }


            strsql = "update Pay_Order set PayState=6 where ID=@ID";
            var ret = TSLobsterAPI.DbHelper.DbExecuteUpdate(this.data.dbConn, strsql, { ID: order.ID });

            strsql = "INSERT INTO Pay_RefundOrder (SubMchId ,OrderNo ,BusinessOrderNo ,TradeNo ,RefundDate ,RefundFee ,SettlementRefundFee\
                    ,RefundNo ,RefundStatus ,RefundDesc,WorkId)\
              VALUES  (@SubMchId,@OrderNo,@BusinessOrderNo,@TradeNo,getdate(),@RefundRealFee,@RefundRealFee,@RefundNo,@RefundStatus,@RefundDesc,@WorkId)";
            var refundNo = "R" + this.service.generateTimeReqestNumber()

            let dbparams2 = {
                SubMchId: model.SubMchId,
                OrderNo: order.OrderNo,//支付系统订单号
                BusinessOrderNo: order.BusinessOrderNo,//业务系统订单号
                TradeNo: order.TradeNo,//交易系统流水号
                RefundRealFee: model.RefundRealFee,
                RefundNo: refundNo,//支付系统退款号
                RefundStatus: order.PayType == 3 ? 1 : 0,
                RefundDesc: model.RefundDesc,
                WorkId: this.data.WorkId
            }

            ret = TSLobsterAPI.DbHelper.DbExecuteUpdate(this.data.dbConn, strsql, dbparams2);

            var refundobject = {
                AppID: payment.AppID,
                MchId: payment.MchId,
                ApiKey: payment.ApiKey,
                RefundNotifyUrl: payment.RefundNotifyUrl,
                SubMchId: payment.SubMchId,
                OrderNo: order.OrderNo,
                RefundNo: refundNo,
                PayFee: order.TotalFee * 100,
                RefundRealFee: model.RefundRealFee * 100,
                RefundDesc: model.RefundDesc,
            }
            //调用微信接口
            let res = TSLobsterAPI.Http.Post('/pay/v1/pay/Refund', refundobject);
            if (res['code'] != 0) {
                throw res['msg'];
            }
            this.data.dbConn.CommitTransaction();
            return { result: true };
        }
        catch (e) {
            this.data.dbConn.RollbackTransaction();
            throw e;
        }
    }

    /**
     * 获取退款详情
     */
    getrefundlistdetail(orderNo) {

        var strsql = "SELECT * from Pay_RefundOrder WHERE WorkId=@WorkId and RefundStatus=1 and OrderNo like @orderNo ";
        var dbparams = {
            WorkId: this.data.WorkId,
            orderNo: '%' + orderNo + '%'
        }
        var data = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, dbparams);
        return { data: data }
    }
}

/**
 * 退费服务
 */
class refundService {
    public data = {
        dbConn: TSLobsterAPI.Program.GetDbConn(),
        WorkId: 1,
        AppId: 1
    }

    public service: tspayService;
    public dao: tspayDao;

    constructor(workid: number, appid: number) {
        this.data.WorkId = workid;
        this.data.AppId = appid;

        this.service = new tspayService(this.data.WorkId);
        this.dao = new tspayDao(this.data.WorkId);

    }

    /**
     * 获取退款记录
     */
    getrefundlist(page, limit, orderNo, refundStatus, sdate, edate) {
        var pageInfo = {
            key: "Id Desc",
            page: page,
            perPage: limit,
            totalRecord: 100
        };
        var strsql = "SELECT * from Pay_RefundOrder a WHERE a.WorkId=@workid ";
        var dbparams = {
            workid: this.data.WorkId,
            orderNo: '%' + orderNo + '%',
            refundStatus: refundStatus,
            sdate: sdate + " 00:00:01",
            edate: edate + " 23:59:59"
        }
        if ((orderNo || "") != "") {
            strsql += " and a.RefundNo Like @orderNo or a.OrderNo Like @orderNo";
        }
        if (refundStatus > -1) {
            strsql += " and a.RefundStatus =  @refundStatus";
        }
        if ((sdate || "") != "") {
            strsql += " and a.RefundDate >=  @sdate";
        }
        if ((edate || "") != "") {
            strsql += " and a.RefundDate <=  @edate";
        }
        var data = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, dbparams, pageInfo);
        return { data: data, count: pageInfo.totalRecord };
    }
}

/**
 * 账单服务
 */
class billService {
    public data = {
        dbConn: TSLobsterAPI.Program.GetDbConn(),
        WorkId: 1,
        AppId: 1
    }

    public service: tspayService;
    public dao: tspayDao;

    constructor(workid: number, appid: number) {
        this.data.WorkId = workid;
        this.data.AppId = appid;

        this.service = new tspayService(this.data.WorkId);
        this.dao = new tspayDao(this.data.WorkId);

    }

    gettransactionlist(page, limit, type, sdate, edate) {
        var pageInfo = {
            key: "TransactionDate",
            page: page,
            perPage: limit,
            totalRecord: 100
        };
        var strsql = '';
        if (type == 1) {
            strsql = "select * from (select OrderDate as TransactionDate,SubMchId,OrderNo,BusinessOrderNo,TradeNo,'' as RefundNo,'' as BusinessRefundNo,'' as RefundTradeNo, TotalFee as PayFee, 0 as RefundFee, WorkId from Pay_Order where PayState in(2,3,4)\
                        union all \
                        select RefundDate as TransactionDate,SubMchId,OrderNo,BusinessOrderNo,'' as TradeNo, RefundNo,BusinessRefundNo,TradeNo as RefundTradeNo, 0 as PayFee,RefundFee,WorkId from Pay_RefundOrder where RefundStatus =1\
                        ) a where a.WorkId=@workid";
        } else if (type == 2) {
            strsql = "select * from (select OrderDate as TransactionDate,SubMchId,OrderNo,BusinessOrderNo,TradeNo,'' as RefundNo,'' as BusinessRefundNo,'' as RefundTradeNo, TotalFee as PayFee, 0 as RefundFee, WorkId from Pay_Order where PayState in(2,3,4)\
            ) a where a.WorkId=@workid";
        } else if (type == 3) {
            strsql = "select * from (select RefundDate as TransactionDate,SubMchId,OrderNo,BusinessOrderNo,'' as TradeNo, RefundNo,BusinessRefundNo,TradeNo as RefundTradeNo, 0 as PayFee,RefundFee,WorkId from Pay_RefundOrder where RefundStatus =1\
            ) a where a.WorkId=@workid";
        }
        var dbparams = {
            workid: this.data.WorkId,
            sdate: sdate + " 00:00:01",
            edate: edate + " 23:59:59"
        }
        if ((sdate || "") != "") {
            strsql += " and a.TransactionDate >=  @sdate";
        }
        if ((edate || "") != "") {
            strsql += " and a.TransactionDate <=  @edate";
        }
        var data = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, dbparams, pageInfo);
        return { data: data, count: pageInfo.totalRecord };
    }

    getreport(sdate, edate, type) {
        return { result: true };
    }
}

/**
 * 实时数据服务
 */
class realtimeService{
    public data = {
        dbConn: TSLobsterAPI.Program.GetDbConn(),
        WorkId: 1,
        AppId: 1
    }

    public service: tspayService;
    public dao: tspayDao;

    constructor(workid: number, appid: number) {
        this.data.WorkId = workid;
        this.data.AppId = appid;

        this.service = new tspayService(this.data.WorkId);
        this.dao = new tspayDao(this.data.WorkId);

    }

    getchartdata (type) {
        if (type == 0) {

            var strsql = "select a.OrderDate,sum(a.TotalFee) as TotalFee,count(0) as num from (select CONVERT(varchar(13),OrderDate,120) as OrderDate,TotalFee from Pay_Order where PayState>1 \
        and OrderDate <=CONVERT(varchar(13), dateadd(HOUR,-1, GETDATE()) ,120)+':00:00'\
        and OrderDate>=CONVERT(varchar(13), dateadd(HOUR,-24, GETDATE()) ,120)+':00:00' and WorkId=@workid) as  a\
        group by a.OrderDate\
        order by a.OrderDate";

            var ydata1 = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, {workid:this.data.WorkId});

            strsql = "select a.OrderDate,sum(a.TotalFee) as TotalFee,count(0) as num from (select CONVERT(varchar(13),OrderDate,120) as OrderDate,TotalFee from Pay_Order where PayState>1  \
        and OrderDate <=CONVERT(varchar(13), dateadd(HOUR,-25, GETDATE()) ,120)+':00:00'\
        and OrderDate>=CONVERT(varchar(13), dateadd(HOUR,-48, GETDATE()) ,120)+':00:00' and WorkId=@workid) as  a\
        group by a.OrderDate\
        order by a.OrderDate";

            var ydata2 = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, {workid:this.data.WorkId});
            return {
                ydata1: ydata1,
                ydata2: ydata2
            }
        } else if (type == 1) {
            var self = this;
            var strsql = "select a.OrderDate,count(0) as TotalFee from (select CONVERT(varchar(13),OrderDate,120) as OrderDate,TotalFee from Pay_Order where PayState=2 \
        and OrderDate <=CONVERT(varchar(13), dateadd(HOUR,-1, GETDATE()) ,120)+':00:00'\
        and OrderDate>=CONVERT(varchar(13), dateadd(HOUR,-24, GETDATE()) ,120)+':00:00' and WorkId=@workid) as  a\
        group by a.OrderDate\
        order by a.OrderDate";
            var ydata1 = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, {workid:this.data.WorkId});

            strsql = "select a.OrderDate,count(0) as TotalFee from (select CONVERT(varchar(13),OrderDate,120) as OrderDate,TotalFee from Pay_Order where PayState=2 \
        and OrderDate <=CONVERT(varchar(13), dateadd(HOUR,-25, GETDATE()) ,120)+':00:00'\
        and OrderDate>=CONVERT(varchar(13), dateadd(HOUR,-48, GETDATE()) ,120)+':00:00' and WorkId=@workid) as  a\
        group by a.OrderDate\
        order by a.OrderDate";

            var ydata2 = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, {workid:this.data.WorkId});
            return {
                ydata1: ydata1,
                ydata2: ydata2
            }
        }
    }
}